package com.lateam2010.send.server;


import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.lateam2010.register.server.PasswordException;
import com.lateam2010.register.server.RegisterServiceImpl;
import com.lateam2010.send.client.GreetingService;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public final class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {

	public GreetingServiceImpl() {
	}
	
	public boolean greetServer(String password, boolean toAll, String from, String subject, String body) throws IOException {
		List<InternetAddress> emails = new LinkedList<InternetAddress>();
		if (toAll) {
			String[][] all;
			try {
				all = RegisterServiceImpl.listAll(password);
			} catch (PasswordException e){
				return false;
			}
			
			for (String[] a : all) {
				emails.add(new InternetAddress(a[0], a[1]));
			}
		}
		
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        try {
            Message msg = new MimeMessage(session);
            InternetAddress aa = new InternetAddress("david.fauthoux@gmail.com", from + " [via le blog de la Team 2010]");
            msg.setFrom(aa);
            msg.addRecipient(Message.RecipientType.TO, aa);
            for (InternetAddress a : emails) {
	            msg.addRecipient(Message.RecipientType.BCC, a);
            }
            msg.setSubject(subject);
            msg.setText("- Message de la part de " + from + ", envoyé via le blog : http://lateam2010.appspot.com -\n\n" + body);
            Transport.send(msg);
        } catch (AddressException e) {
        	throw new IOException(e);
        } catch (MessagingException e) {
        	throw new IOException(e);
        }
        return true;
	}
}
